import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { useAuth } from '../contexts/AuthContext';
import { getUserDesigns, Design, getDesignStats } from '../services/design';

interface DesignStatsData {
  total: number;
  completed: number;
  processing: number;
  failed: number;
  pending: number;
}

interface DesignStatisticsProps {
  onCreateDesign?: () => void;
}

const DesignStatistics: React.FC<DesignStatisticsProps> = ({ onCreateDesign }) => {
  const { user, isAuthenticated } = useAuth();
  const [designs, setDesigns] = useState<Design[]>([]);
  const [designStats, setDesignStats] = useState<DesignStatsData | null>(null);
  const [statsLoading, setStatsLoading] = useState(false);
  const [statsError, setStatsError] = useState<string | null>(null);
  const [designsLoading, setDesignsLoading] = useState(false);
  const [designsError, setDesignsError] = useState<string | null>(null);

  // 加载设计统计数据
  const loadDesignStats = async () => {
    try {
      setStatsLoading(true);
      setStatsError(null);
      
      if (!isAuthenticated) {
        setStatsError('Please log in to view your design statistics');
        return;
      }
      
      const response = await getDesignStats();
      if (response.success) {
        setDesignStats(response.data);
      } else {
        setStatsError(response.message || 'Failed to load design statistics');
      }
    } catch (err: any) {
      console.error('Error loading design statistics:', err);
      setDesignStats(null);
      if (err.message?.includes('401') || err.message?.includes('认证')) {
        setStatsError('Login session expired, please log in again');
      } else {
        setStatsError('Failed to load design statistics');
      }
    } finally {
      setStatsLoading(false);
    }
  };

  // 加载设计列表
  const loadDesigns = async () => {
    try {
      setDesignsLoading(true);
      setDesignsError(null);
      
      if (!isAuthenticated) {
        setDesignsError('Please log in to view your designs');
        return;
      }
      
      const response = await getUserDesigns();
      if (response.success) {
        setDesigns(response.data.designs);
      } else {
        setDesignsError(response.message || 'Failed to load designs');
      }
    } catch (err: any) {
      console.error('Error loading designs:', err);
      setDesigns([]);
      if (err.message?.includes('401') || err.message?.includes('认证')) {
        setDesignsError('Login session expired, please log in again');
      } else {
        setDesignsError('Failed to load designs');
      }
    } finally {
      setDesignsLoading(false);
    }
  };

  // 组件挂载时加载数据
  useEffect(() => {
    if (user && isAuthenticated) {
      loadDesignStats();
      loadDesigns();
    }
  }, [user, isAuthenticated]);

  // 格式化日期
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // 获取状态颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed':
        return 'text-green-600 bg-green-100';
      case 'processing':
        return 'text-yellow-600 bg-yellow-100';
      case 'failed':
        return 'text-red-600 bg-red-100';
      default:
        return 'text-gray-600 bg-gray-100';
    }
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
      className="space-y-6"
    >
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6 md:p-8">
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-6">
          <h2 className="text-2xl font-bold text-gray-900 mb-4 sm:mb-0">Design Statistics</h2>
          <button
            onClick={() => {
              loadDesignStats();
              loadDesigns();
            }}
            className="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
          >
            <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
            Refresh
          </button>
        </div>
        
        {/* 加载状态 */}
        {statsLoading && (
          <div className="flex items-center justify-center py-8">
            <div className="w-8 h-8 border-4 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
            <span className="ml-3 text-gray-600">Loading statistics...</span>
          </div>
        )}
        
        {/* 错误状态 */}
        {statsError && (
          <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
            <div className="flex items-center">
              <svg className="w-5 h-5 text-red-400 mr-2" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
              </svg>
              <p className="text-red-800">{statsError}</p>
            </div>
          </div>
        )}
        
        {/* 统计卡片网格 */}
        {!statsLoading && !statsError && (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6 mb-8">
            <div className="bg-gradient-to-r from-blue-500 to-blue-600 rounded-lg p-4 md:p-6 text-white">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-blue-100 text-sm">Total Designs</p>
                  <p className="text-2xl md:text-3xl font-bold">{designStats?.total || 0}</p>
                </div>
                <svg className="w-8 h-8 text-blue-200" fill="currentColor" viewBox="0 0 20 20">
                  <path d="M4 3a2 2 0 100 4h12a2 2 0 100-4H4z"/>
                  <path fillRule="evenodd" d="M3 8h14v7a2 2 0 01-2 2H5a2 2 0 01-2-2V8zm5 3a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z" clipRule="evenodd"/>
                </svg>
              </div>
            </div>
            
            <div className="bg-gradient-to-r from-green-500 to-green-600 rounded-lg p-4 md:p-6 text-white">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-green-100 text-sm">Completed</p>
                  <p className="text-2xl md:text-3xl font-bold">{designStats?.completed || 0}</p>
                </div>
                <svg className="w-8 h-8 text-green-200" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd"/>
                </svg>
              </div>
            </div>
            
            <div className="bg-gradient-to-r from-red-500 to-red-600 rounded-lg p-4 md:p-6 text-white">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-red-100 text-sm">Failed</p>
                  <p className="text-2xl md:text-3xl font-bold">{designStats?.failed || 0}</p>
                </div>
                <svg className="w-8 h-8 text-red-200" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd"/>
                </svg>
              </div>
            </div>
            
            <div className="bg-gradient-to-r from-yellow-500 to-yellow-600 rounded-lg p-4 md:p-6 text-white">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-yellow-100 text-sm">Processing</p>
                  <p className="text-2xl md:text-3xl font-bold">{designStats?.processing || 0}</p>
                </div>
                <svg className="w-8 h-8 text-yellow-200" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z" clipRule="evenodd"/>
                </svg>
              </div>
            </div>
          </div>
        )}
        
        {/* 最近设计活动 */}
        <div>
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Recent Design Activity</h3>
          
          {designsLoading && (
            <div className="flex items-center justify-center py-8">
              <div className="w-6 h-6 border-4 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
              <span className="ml-3 text-gray-600">Loading recent designs...</span>
            </div>
          )}
          
          {designsError && (
            <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-4">
              <div className="flex items-center">
                <svg className="w-5 h-5 text-yellow-400 mr-2" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                </svg>
                <p className="text-yellow-800">{designsError}</p>
              </div>
            </div>
          )}
          
          {!designsLoading && !designsError && (
            <div className="space-y-3">
              {Array.isArray(designs) && designs.slice(0, 5).map((design) => (
                <div key={design.id} className="flex flex-col sm:flex-row sm:items-center justify-between p-4 bg-gray-50 rounded-lg">
                  <div className="flex items-center space-x-3 mb-2 sm:mb-0">
                    <div className="w-12 h-12 bg-gray-200 rounded-lg overflow-hidden flex-shrink-0">
                      {design.originalImageUrl && (
                        <img
                          src={design.originalImageUrl}
                          alt="Design"
                          className="w-full h-full object-cover"
                        />
                      )}
                    </div>
                    <div>
                      <p className="font-medium text-gray-900">{design.roomType} - {design.designStyle}</p>
                      <p className="text-sm text-gray-500">{formatDate(design.createdAt)}</p>
                    </div>
                  </div>
                  <div className="flex items-center space-x-3">
                    <span className={`px-2 py-1 rounded-full text-xs ${getStatusColor(design.status)}`}>
                      {design.status === 'completed' ? 'Completed' : design.status === 'processing' ? 'Processing' : design.status === 'failed' ? 'Failed' : design.status}
                    </span>
                    <span className="text-sm text-gray-600">{design.creditsUsed} Credits</span>
                  </div>
                </div>
              ))}
            </div>
          )}
          
          {!designsLoading && !designsError && (!Array.isArray(designs) || designs.length === 0) && (
            <div className="text-center py-8">
              <svg className="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v4a2 2 0 01-2 2h-2a2 2 0 00-2-2z" />
              </svg>
              <h3 className="mt-2 text-sm font-medium text-gray-900">No Design Data</h3>
              <p className="mt-1 text-sm text-gray-500">Start creating your first design!</p>
              {onCreateDesign && (
                <div className="mt-6">
                  <button
                    onClick={onCreateDesign}
                    className="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700"
                  >
                    Create Design
                  </button>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </motion.div>
  );
};

export default DesignStatistics;